package com.kerbores.agent.client;

import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.net.TcpConnector;

import com.kerbores.agent.InvokeData;
import com.kerbores.agent.Method;
import com.kerbores.agent.Result;

public class AgentClient {

	protected Log log = Logs.get();

	private String ip;
	private int port;

	/**
	 * @param ip
	 * @param port
	 */
	public AgentClient(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}

	public Result invoke(Method method, NutMap params) {
		try {
			InvokeData data = new InvokeData(method, params);
			TcpConnector connector = new TcpConnector(ip, port);
			connector.connect();
			connector.writeLine(Json.toJson(data, JsonFormat.compact()));
			connector.writeLine("");// 发送空行标识请求结束
			String info = connector.readLine();
			return Lang.map2Object(Lang.map(info), Result.class);
		} catch (Exception e) {
			log.error(e);
			return Result.exception(e);
		}
	}
}
